import icon from '@/assets/down_arrow.png';
import { langList, replaceQueryParam } from '@/utils';
import { Space } from 'antd';
import 'dayjs/locale/zh-tw';
import React, { useMemo } from 'react';
import { history, SelectLang, setLocale, useIntl } from 'umi';
type Props = {
  wordCss?: React.CSSProperties;
  SelectCss?: React.CSSProperties;
  icons?: string;
  logo?: string;
  localOverlayClassName?: string;
};

const Locale: React.FC<Props> = ({ wordCss, SelectCss, icons, logo, localOverlayClassName }) => {
  const intl = useIntl();
  const lang = intl.locale;

  const val = useMemo(() => {
    return langList.find((item) => item.lang == lang);
  }, [lang]);

  const { label: langLable } = val || {};
  return (
    <SelectLang
      postLocalesData={() => langList.filter((item) => item.lang != lang)}
      style={{ padding: 0, ...SelectCss }}
      // @ts-ignore
      overlayClassName={`selectLang ${localOverlayClassName}`}
      placement="bottom"
      onItemClick={(params) => {
        const { key } = params;
        const isEn = key == 'en-US';

        const currentUrl = new URL(window.location.href);
        const searchParams = currentUrl.search;
        const hash = currentUrl.hash;
        const pathName = currentUrl.pathname.replace('/en', '') || '/';
        currentUrl.pathname = isEn ? `/en${pathName}` : pathName;
        if (hash) {
          currentUrl.hash = `${hash.split('?')[0]}${replaceQueryParam(
            `?${hash.split('?')[1]}`,
            'lang',
            key,
          )}`;
        } else {
          currentUrl.search = replaceQueryParam(searchParams, 'lang', key);
        }
        setLocale(lang);
        history.replace(currentUrl.toString());
      }}
      icon={
        <Space size={6} style={{ marginTop: -2 }} align="center">
          {logo ? <img src={logo} height={17} /> : null}
          <div style={{ fontSize: 16, ...wordCss, filter: 'none' }}>{langLable}</div>
          <img src={icons || icon} style={{ ...wordCss }} width={18} />
        </Space>
      }
    />
  );
};

export default Locale;
